// ==UserScript==
// @name         gitee.com脚本
// @namespace    http://tampermonkey.net/
// @version      v1.0
// @description  try to take over the world!
// @author       laoyu
// @match        https://gitee.com/*
// @icon         https://gitee.com/assets/favicon_message.ico?1581387642851
// @grant        none
// ==/UserScript==

(function() {
    'use strict';

    // storage
    const storage = {};

    // 判断当前是不是代码提交列表页面
    let is_commit_list_page_try_count = 0;
    (function is_commit_list_page() {
        if (is_commit_list_page_try_count > 20) {
            return ;
        }
        is_commit_list_page_try_count++;
        let tmp = document.querySelector('.project-commits-filter .right-dropdown');
        if (!tmp) {
            setTimeout(is_commit_list_page, 200);
        }
        setShowCodeLineBtn(tmp);
    })();

    // 设置展示代码行数按钮的逻辑
    function setShowCodeLineBtn(d) {
        // 构建按钮的dom
        let new_button = document.createElement('div');
        new_button.className = 'ui orange button';
        new_button.innerText = '展示代码量';
        // 绑定点击函数
        new_button.addEventListener('click', showEveryDayCodeLineBtn);
        // 插入到页面中
        d.parentNode.insertBefore(new_button, d);
        // 本脚本的样式
        let style = document.createElement('style');
        style.innerText = `
            .my-commit-group-title {
                user-select: none;
                cursor: pointer;
            }
            .my-commit-group-title:hover {
                color: #50586b;
            }
        `;
        document.head.appendChild(style);
    }

    function showEveryDayCodeLineBtn() {
        // 这个按钮只能点击一次
        if (storage.show_everyday_code_line_btn) {
            return ;
        }
        storage.show_everyday_code_line_btn = true;
        // 获取每一个需要添加提交按钮的行并添加相应的按钮
        // 获取提交列表
        let commit_list = document.querySelector("#commits-list > .commit-list");
        if (!commit_list) {
            alert('未检查到当前页面有提交列表');
            return ;
        }
        // 循环获取每一个提交的信息
        for (let i = 0; i < commit_list.children.length; i++) {
            let commit_group_header = commit_list.children[i].querySelector('.header');
            console.log(commit_group_header);
            let header_btn = commit_group_header.querySelector('.commit-group-title');
            header_btn.classList.add('my-commit-group-title');
            header_btn.setAttribute('clicked', 'false');
            header_btn.addEventListener('click', async () => {
                // 防止点两下
                if (header_btn.getAttribute('clicked') == 'true') {
                    return ;
                }
                header_btn.setAttribute('clicked', 'true');
                // 新建一个div用于显示总的代码量
                let total_code_div = document.createElement('div');
                total_code_div.style.display = 'inline-block';
                total_code_div.style.fontWeight = '900';
                let total_add_line_count = 0;
                let total_sub_line_count = 0;
                total_code_div.innerHTML = `
                    <span style="color: #00b400; margin-left: 0.5em">+${total_add_line_count}</span>
                    <span style="color: #d92b2f; margin-left: 0.5em">-${total_sub_line_count}</span>
                `;
                commit_group_header.appendChild(total_code_div);
                // 获取每一个提交行
                let commit_group = commit_list.children[i].querySelector('.content');
                for (let i = 0; i < commit_group.children.length; i++) {
                    let item = commit_group.children[i];
                    console.log(item);
                    let data_src_url = item.getAttribute('data-html-url');
                    let req_url = `https://gitee.com${data_src_url}`;
                    let data = await syncFetch(req_url, {
                        "headers": {
                            "accept": "application/json, text/plain, */*",
                            "accept-language": "zh-CN,zh;q=0.9",
                            "cache-control": "no-cache",
                            "pragma": "no-cache",
                            "x-requested-with": "XMLHttpRequest",
                            "Referer": req_url,
                            "Referrer-Policy": "unsafe-url"
                        },
                        "body": null,
                        "method": "GET"
                    });
                    if (data.success) {
                        data = data.data;
                        let add_line_count = data.added_lines;
                        let sub_line_count = data.removed_lines;
                        let mof_file_count = data.count;
                        // 构建新的dom
                        let new_dom = document.createElement('span');
                        new_dom.style.fontWeight = '900';
                        new_dom.innerHTML = `<span style="margin-left: 1em">${mof_file_count}个文件发生了变化，影响行数：</span><span style="color: #00b400; margin-left: 0.5em">+${add_line_count}</span><span style="color: #d92b2f; margin-left: 0.5em">-${sub_line_count}</span>`;
                        total_add_line_count += add_line_count;
                        total_sub_line_count += sub_line_count;
                        total_code_div.innerHTML = `
                            <span style="color: #00b400; margin-left: 0.5em">+${total_add_line_count}</span>
                            <span style="color: #d92b2f; margin-left: 0.5em">-${total_sub_line_count}</span>
                        `;
                        // 将dom渲染到页面中
                        item.querySelector('.commit-content .commit-meta').appendChild(new_dom);
                    } else {
                        console.error('获取提交代码量信息失败');
                    }
                }
            });
        }
    }

    // 公共函数，输出日志
    function info(...args) {
        console.log(...args);
    }

    // 公共函数，同步请求
    function syncFetch(...args) {
        return new Promise((resolve) => {
            fetch(...args).then(async res => {
                resolve({success: true, data: await res.json()});
            }).catch(err => {
                resolve({success: false, err});
            });
        });
    }
})();